package org.banyan.senior.idempotent.config;

import org.banyan.senior.idempotent.filter.RepeatableFilter;
import org.banyan.senior.idempotent.interceptor.DuplicateRequestHandlerInterceptor;
import org.banyan.senior.idempotent.interceptor.InterfaceIdempotenceHandlerInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author metalsbanyan
 * @version 1.0
 * @description:
 * @date 2023/7/21 11:21
 */
@Configuration
@ConditionalOnClass({DispatcherServlet.class, RedisAutoConfiguration.class})
@ComponentScan(basePackages = "org.banyan.senior.idempotent")
public class RedisTokenAutoConfiguration implements WebMvcConfigurer {


    @Bean
    public DuplicateRequestHandlerInterceptor duplicateRequestHandlerInterceptor(){
        return new DuplicateRequestHandlerInterceptor();
    }

    @Bean
    public InterfaceIdempotenceHandlerInterceptor interfaceIdempotenceHandlerInterceptor(){
        return new InterfaceIdempotenceHandlerInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(duplicateRequestHandlerInterceptor()).order(1).addPathPatterns("/*");
        registry.addInterceptor(interfaceIdempotenceHandlerInterceptor()).order(2).addPathPatterns("/*");
    }

    /**
     * 生成防重复提交过滤器（重写request）
     */
    @Bean
    public FilterRegistrationBean<RepeatableFilter> createRepeatableFilter() {
        FilterRegistrationBean<RepeatableFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new RepeatableFilter());
        registration.addUrlPatterns("/*");
        registration.setName("repeatableFilter");
        registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
        return registration;
    }
}
